package com.itouchtv.yang.core.tools;

import java.io.*;
import java.util.Objects;
import java.util.Properties;

public class ConfigManager {
    private static Properties properties = new Properties();
    private static String filePath = "config/config.properties";
    private static InputStream in;
    private static OutputStream os;

    public synchronized static String getProperty(String key, String defualtValue) {
        String path = ClassPath.getClassPath();

        try {
            in = new FileInputStream(path+filePath);
            properties.load(in);
        } catch (IOException e) {
            Log.logger.error("读取:" +path + filePath +"\n"+
                    "失败，请检查"+e.fillInStackTrace());
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                Log.logger.error("配置表IO关闭失败"+"\n"+
                        e.fillInStackTrace());
                e.printStackTrace();
            }
        }
        String s = properties.getProperty(key, defualtValue);
        if (Objects.isNull(s)||Objects.equals(s,"")){
            Log.logger.error("没有找到:"+key+"请检查config.properties");
        }
        return s;
    }

    public synchronized static void setProperty(String key, String value) {
        String path = ClassPath.getClassPath();

        try {
            in = new FileInputStream(path+filePath);
            properties.load(in);
            os = new FileOutputStream(path+filePath);
            properties.setProperty(key, value);
            properties.store(os, "update:" + key);
        } catch (IOException e) {
            Log.logger.error("读取:" +path + filePath + "失败，请检查"+"\n"
                    +e.fillInStackTrace());
        } finally {
            try {
                in.close();
                os.close();
            } catch (IOException e) {
                Log.logger.error("配置表IO关闭失败"+"\n"+
                        e.fillInStackTrace());
                e.printStackTrace();
            }
        }
    }
}
